﻿using System;
using System.Collections.Generic;
using System.IO;
using Baidu.Aip.Speech;

namespace Baidu.Aip.Demo
{
    internal class SpeechDemo
    {
        private readonly Asr _asrClient;
        private readonly Tts _ttsClient;

        public SpeechDemo()
        {
            _asrClient = new Asr("FgeNKtnM927MtDCtAtbeBOqG", "hpqgl6iqS4Hk8eBNdGzgWFAGIz9NcBEA");
            _ttsClient = new Tts("FgeNKtnM927MtDCtAtbeBOqG", "hpqgl6iqS4Hk8eBNdGzgWFAGIz9NcBEA");
        }

        /// <summary>
        /// 识别本地文件,支持
        /// </summary>
        /// <param name="path"></param>
        public void AsrData(string path)
        {
            var data = File.ReadAllBytes(path);
            var result = _asrClient.Recognize(data, "wav", 16000);
            Console.Write(result);
        }

        // 识别URL中的语音文件
        public void AsrUrl()
        {
            var result = _asrClient.Recoginze(
                "http://xxx.com/待识别的pcm文件地址",
                "http://xxx.com/识别结果回调地址",
                "pcm",
                16000);
            Console.WriteLine(result);
        }

        /// <summary>
        /// 语音合成
        /// </summary>
        /// <param name="word"></param>
        public void Tts(string word)
        {
            // 可选参数
            var option = new Dictionary<string, object>
            {
                {"spd", 3}, // 语速 0-9,0最慢，9最快
                {"vol", 7}, // 音量
                {"per", 1} // 发音人，0:普通女生，1：普通男生，2：特别男生，3：情感男生，4：情感度丫丫童声
            };
            var result = _ttsClient.Synthesis(word, option);

            if (result.ErrorCode == 0) // 或 result.Success
                File.WriteAllBytes("E://合成的语音文件.mp3", result.Data);
        }
    }
}